<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="清单编码" prop="boqCode">
        <el-input
          v-model="queryParams.boqCode"
          placeholder="请输入清单编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="清单名称" prop="boqName">
        <el-input
          v-model="queryParams.boqName"
          placeholder="请输入清单名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :value="item.value"
            :label="item.label"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['project:arrange:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleArrange"
          :disabled="this.arrangeList.length == 0"
          v-hasPermi="['project:arrange:edit']"
        >整理</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handleComplementAll"
          :disabled="this.arrangeList.length == 0"
          v-hasPermi="['project:arrange:edit']"
        >自动补全</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-close"
          size="mini"
          @click="handleIgnoreWarnings"
          :disabled="this.arrangeList.length == 0"
          v-hasPermi="['project:arrange:edit']"
        >忽略警告</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          :disabled="this.arrangeList.length == 0"
          v-hasPermi="['project:arrange:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleClean"
          :disabled="this.arrangeList.length == 0"
          v-hasPermi="['project:arrange:remove']"
        >清空</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleGyHouseImport"
          v-hasPermi="['project:arrange:import']"
        >根牙房建</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="arrangeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="清单编码" align="left" prop="boqCode" width="80" />
      <el-table-column label="清单名称" align="left" prop="boqName" width="150" show-overflow-tooltip />
      <el-table-column label="上级清单" align="left" prop="parentCode" width="80" :formatter="formatParentCode"/>
      <el-table-column label="祖籍列表" align="left" prop="ancestors" width="100" show-overflow-tooltip/>
      <el-table-column label="排序" align="center" prop="orderNum" width="80" />
      <el-table-column label="级别" align="center" prop="level" width="80" />
      <el-table-column label="叶节点" align="center" prop="leafNode" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.leafNode"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status == 0">正常</el-tag>
          <el-tag type="warning" v-else-if="scope.row.status < 0">警告</el-tag>
          <el-tag type="danger" v-else>异常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="原因" align="left" prop="reason" width="100" show-overflow-tooltip>
      </el-table-column>
      <el-table-column label="是否补全" align="center" prop="leafNode" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.autoCompletion"/>
        </template>
      </el-table-column>
      <el-table-column label="补全清单" align="center" prop="completionCode" width="100" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="handleIgnore(scope.row)"
            v-if="scope.row.status == -1"
            v-hasPermi="['project:arrange:edit']"
          >忽略</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-shopping-cart-full"
            @click="handleComplement(scope.row)"
            v-if="scope.row.status == -2"
            v-hasPermi="['project:arrange:edit']"
          >补全</el-button>
        </template>
      </el-table-column>
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="数量" align="center" prop="amount" />
      <el-table-column label="单价" align="center" prop="price" />
      <el-table-column label="金额" align="center" prop="total" />
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 清单导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 根牙房建导入对话框 -->
    <el-dialog :title="gyHouse.title" :visible.sync="gyHouse.open" width="400px" append-to-body>
      <el-upload
        ref="gyHouse"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="gyHouse.headers"
        :action="gyHouse.url"
        :disabled="gyHouse.isUploading"
        :on-progress="handleGyFileUploadProgress"
        :on-success="handleGyFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitGyHouseFileForm">确 定</el-button>
        <el-button @click="gyHouse.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listArrange, importTemplate, arrange, clean, ignore, beforeComplement, beforeAutoComplementAll, ignoreWarnings, autoComplementAll, autoComplement, exportCheck, exportArrange } from "@/api/project/arrange";
import { getToken } from "@/utils/auth";
import {delMeterage} from "@/api/engineering/meterage";

export default {
  name: "Arrange",
  dicts: ['sys_yes_no'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 清单整理表格数据
      arrangeList: [],
      // 弹出层标题
      title: "",
      // 状态列表
      statusOptions: [{
        value: 0,
        label: '正常'
      }, {
        value: 1,
        label: '异常'
      }, {
        value: 2,
        label: '警告'
      }],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: undefined,
        boqCode: undefined,
        boqName: undefined,
      },
      // 清单导入参数
      upload: {
        // 是否显示弹出层（清单导入）
        open: false,
        // 弹出层标题（清单导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { token: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/project/arrange/importData"
      },
      gyHouse: {
        // 是否显示弹出层（清单导入）
        open: false,
        // 弹出层标题（清单导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { token: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/project/arrange/importGyHouseData"
      }

    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询清单整理列表 */
    getList() {
      this.loading = true;
      listArrange(this.queryParams).then(response => {
        this.arrangeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    formatParentCode(row, column, value) {
      if (value == '0') {
        return '';
      } else {
        return value;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.boqId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 整理按钮操作 */
    handleArrange() {
      const loading = this.$loading({
        lock: true,
        text: '清单整理中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      arrange().then(response => {
        this.getList();
        this.$modal.msgSuccess("整理成功");
        loading.close();
      });
    },
    /** 自动补全按钮操作 */
    handleComplementAll() {
      beforeAutoComplementAll().then(response => {
        const loading = this.$loading({
          lock: true,
          text: '清单补全中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        autoComplementAll().then(response => {
          this.getList();
          this.$modal.msgSuccess("操作成功");
          loading.close();
        });
      });
    },
    // 忽略警告
    handleIgnoreWarnings() {
      this.$modal.confirm('确定忽略所有警告信息（不包含清单编号缺省数据）？').then(function() {
        return ignoreWarnings();
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    },
    /** 清空按钮操作 */
    handleClean() {
      clean().then(response => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "清单导入";
      this.upload.open = true;
    },
    /** 根牙房建导入 */
    handleGyHouseImport() {
      this.gyHouse.title = "根牙房建导入";
      this.gyHouse.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.$download.name(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true, customClass: "myMessageBox" });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 提交上传根牙房建清单
    submitGyHouseFileForm() {
      this.$refs.gyHouse.submit();
    },
    // 文件上传中处理
    handleGyFileUploadProgress(event, file, fileList) {
      this.gyHouse.isUploading = true;
    },
    // 文件上传成功处理
    handleGyFileSuccess(response, file, fileList) {
      this.gyHouse.open = false;
      this.gyHouse.isUploading = false;
      this.$refs.gyHouse.clearFiles();
      this.$download.name(response.msg);
    },
    /** 导出按钮操作 */
    handleExport() {
      // 导出前先检查清单是否存在异常
      exportCheck().then(response => {
        const queryParams = this.queryParams;
        this.$modal.confirm('确认导出所有清单整理数据项？').then(() => {
          this.exportLoading = true;
          return exportArrange(queryParams);
        }).then(response => {
          this.$download.name(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
      })
    },
    /** 忽略按钮操作 */
    handleIgnore(row) {
      const boqId = row.boqId;
      this.$modal.confirm("确认忽略清单编码为" + row.boqCode + "的数据项？").then(() => {
        return ignore(boqId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {})
    },
    /** 补全按钮操作 */
    handleComplement(row) {
      const boqId = row.boqId;
      beforeComplement(boqId).then(response => {
        const arrange = response.data;
        this.$modal.confirm("是否将清单编码" + arrange.boqCode + "作为补全？").then(() => {
          return autoComplement({id: arrange.boqId, bId: boqId});
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("操作成功");
        }).catch(() => {})
      })
    }
  }
};
</script>
